<script setup>
import { ref } from 'vue'
import { useCountdown } from '@vueuse/core'
import Button from './Button.vue'

import { sendEmailCodeApi } from '@/api'
import { message } from 'ant-design-vue'
import { validEmail } from '@/utils/valid'
const props = defineProps({
  email: {
    type: String,
    default: '',
    required: true,
  },
  type: {
    type: Number,
    default: 1, // 类型：1注册2找回密码
  },
})

const countdown = ref(5)
const { remaining, start, stop, reset, isActive } = useCountdown(countdown, {
  onComplete: () => {
    console.log('countdown completed')
    reset()
  },
})
// 校验邮箱并获取验证码
const getCode = async () => {
  validEmail('', props.email)
    .then(() => {
      if (isActive.value) return
      // 获取验证码
      sendEmailCodeApi({
        email: props.email,
        type: props.type,
      }).then(() => {
        start()
        message.success('Verification code sent successfully')
      })
    })
    .catch((err) => {
      message.error(err)
    })
}
</script>
<template>
  <Button @click="getCode">{{
    isActive ? `Try again after ${remaining}s` : 'Get verification code'
  }}</Button>
</template>
